package cn.source.zk.service.impl;

import cn.source.common.core.domain.entity.Customer;
import cn.source.common.utils.SecurityUtils;
import cn.source.zk.domain.entity.ConnectionPoint;
import cn.source.zk.domain.entity.Substation;
import cn.source.zk.domain.entity.SubstationStatVO;
import cn.source.zk.domain.entity.SubstationTypeStatVO;
import cn.source.zk.domain.vo.SubstationConnectionPointVO;
import cn.source.zk.mapper.ZkCustomerMapper;
import cn.source.zk.mapper.ZkSubstationMapper;
import cn.source.zk.service.IZkAreaService;
import cn.source.zk.service.IZkConnectionPointService;
import cn.source.zk.service.IZkSubstationService;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ZkSubstationServiceImpl implements IZkSubstationService {

    @Autowired
    private ZkSubstationMapper substationMapper;

    @Autowired
    private ZkCustomerMapper customerMapper;

    @Autowired
    private IZkAreaService areaService;

    @Autowired
    private IZkConnectionPointService connectionPointService;

    /**
     * 查询变电站分页列表
     *
     * @param substation
     * @return
     */
    public List<Substation> listPage(Substation substation) {
        // 设置地区的所有子级id
        List<Long> child = areaService.getChild(substation.getAreaNum());
        substation.setAreaChildNums(child);

        // 获取当前用户的公司id(用于控制权限)
        substation.setCompanyId(SecurityUtils.getCompanyId());
        log.info("公司ID：{}", SecurityUtils.getCompanyId());
        List<Substation> substationList = substationMapper.selectListPage(substation);
        // 给每个变电站设置地区层级名字
        for (Substation substationItem : substationList) {
            String ancestorName = areaService.getAncestorName(substationItem.getAreaNum());
            substationItem.setAncestorNames(ancestorName);
        }

        return substationList;
    }


    @Override
    public Map<String, Object> getLatest10PointsLineData() {
        List<Map<String, Object>> rawData = substationMapper.selectLatest10Points();

        // 反转列表，使时间为正序（从早到晚）
        Collections.reverse(rawData);

        List<String> dates = new ArrayList<>();
        List<Integer> values = new ArrayList<>();

        for (Map<String, Object> row : rawData) {
            dates.add(row.get("statDate").toString());
            values.add(((Number) row.get("pointValue")).intValue());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("dates", dates);
        result.put("values", values);
        return result;
    }

    /**
     * 返回变电站和并网点的集合
     *
     * @return
     */
    public List<SubstationConnectionPointVO> listPageFold(Substation substation) {


        // 获取当前用户的公司id(用于控制权限)
        substation.setCompanyId(SecurityUtils.getCompanyId());
        log.info("公司ID：{}", SecurityUtils.getCompanyId());
        List<SubstationConnectionPointVO> substationConnectionPointVOS = substationMapper.selectListPageFold(substation, SecurityUtils.getUserId());
        // 给每个变电站设置地区层级名字
        for (SubstationConnectionPointVO substationItem : substationConnectionPointVOS) {
            String ancestorName = areaService.getAncestorName(substationItem.getAreaNum());
            substationItem.setAncestorNames(ancestorName);

            List<Long> substationNums = new ArrayList<>();
            substationNums.add(substationItem.getNum());
            List<ConnectionPoint> bySubstationNums = connectionPointService.getBySubstationNums(substationNums);

            substationItem.setConnectionPointList(bySubstationNums);

        }

        return substationConnectionPointVOS;
        // return substationMapper.selectListPageFold();
    }

    @Override
    public JSONObject getSubstationCountByArea() {
        List<JSONObject> jsonObjects = substationMapper.countSubstationsByArea();

        List<String> dates = new ArrayList<>();
        List<Integer> values = new ArrayList<>();

        for (JSONObject row : jsonObjects) {
            dates.add(row.get("area").toString());
            values.add(((Number) row.get("count")).intValue());
        }

        JSONObject result = new JSONObject();
        result.put("dates", dates);
        result.put("values", values);
        return result;
    }

    @Override
    public List<JSONObject> getDeviceCountBySubstationType() {
        return substationMapper.countDevicesBySubstationType();
    }

    @Override
    public List<JSONObject> getSubstationCountByType() {
        return substationMapper.countSubstationsByType();
    }

    @Override
    public JSONObject getMonthlyAdditions(String timeRange) {
        JSONObject result = new JSONObject();
        result.put("substationCount", substationMapper.countSubstationsThisMonth(timeRange));
        result.put("deviceCount", substationMapper.countDevicesThisMonth(timeRange));
        result.put("month", java.time.LocalDate.now().getYear() + "-" + java.time.LocalDate.now().getMonthValue());
        return result;
    }

    @Override
    public List<Map<String, Object>> getRegionCountForPieChart() {
        return substationMapper.countByRegion();
    }

    @Override
    public List<SubstationTypeStatVO> getTypeDistributionAndYoY() {
        return substationMapper.statTypeDistributionAndYoY();
    }

    /**
     * 新增变电站
     *
     * @param substationList
     * @return
     */
    public int add(List<Substation> substationList) {

        //插入到数据库;
        // return substationMapper.insertBatch(ModifyCustomersAndArea(substationList));
        return substationMapper.insert(substationList.get(0));
    }


    /**
     * 根据num查询变电站
     *
     * @param num
     * @return
     */
    public Substation getByNum(Long num) {
        Substation substation = new Substation();
        substation.setNum(num);
        return substationMapper.selectListPage(substation).get(0);
    }


    /**
     * 修改变电站信息
     *
     * @param substationList
     * @return
     */
    public int edit(List<Substation> substationList) {

        //return substationMapper.updateBatch(ModifyCustomersAndArea(substationList));
        return substationMapper.update(substationList.get(0));

    }

    //修改客户和地区
    public List<Substation> ModifyCustomersAndArea(List<Substation> substationList) {
        for (Substation substation : substationList) {
            //根据customer查询客户信息,设置companyName,contactName,phone;
            Customer customer = customerMapper.getByNum(substation.getCustomerNum());
            substation.setCompanyName(customer.getCompanyName());
            substation.setContactName(customer.getContactName());
            substation.setPhone(customer.getPhone());
            //查询地区祖级列表
            String ancestorName = areaService.getAncestorName(substation.getAreaNum());
            substation.setAncestorNames(ancestorName);
        }

        return substationList;
    }

    /**
     * 批量删除变电站信息
     *
     * @param nums
     * @return
     */
    public int removeBatch(List<Long> nums) {


        return substationMapper.removeBatch(nums);
    }

    /**
     * 校验变电站是否存在
     *
     * @param name
     * @return
     */
    public Boolean checkSubstationExist(String name, Long num) {

        Substation substation = new Substation();
        substation.setSubstationName(name);
        substation.setNum(num);

        int result = substationMapper.checkSubstationExist(substation);

        return result > 0;
    }

    @Override
    public List<SubstationStatVO> getStatsByDimension(String dimension) {
        switch (dimension.toLowerCase()) {
            case "year": return substationMapper.statByYear();
            case "quarter": return substationMapper.statByQuarter();
            case "month": return substationMapper.statByMonth();
            case "week": return substationMapper.statByWeek();
            default: throw new IllegalArgumentException("不支持的时间维度: " + dimension);
        }
    }


}
